/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import bean.Schedule;
import bean.ScheduleType;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Eletro Shopping
 */
public class ScheduleDAO extends GenericDAO {
    
    private static final long serialversionUID = 1L;

    public ScheduleDAO() {
    }
    
   public int addSchedule(Schedule sd) throws SQLException {
        sd.setId(getNextId("SCHEDULE"));
        String query = "INSERT INTO SCHEDULE (ID,ID_ANIMAL,DATE,TYPE,TOTAL) values (?,?,?,?,?)";
        executeCommand(query, sd.getId(), sd.getAnimal().getId(), sd.getDate(), sd.getType().toString(), sd.getTotal());
        return sd.getId();
    }

    public void removeSchedule(int idSchedule) throws SQLException {
        executeCommand("DELETE FROM SCHEDULE WHERE ID = ?", idSchedule);
    }

    public void updateSchedule(Schedule sd) throws SQLException {
        String query = "UPDATE SCHEDULE SET ID_ANIMAL = ?,DATE = ?,TYPE = ?,TOTAL = ? WHERE ID = ?";
        executeCommand(query, sd.getAnimal().getId(), sd.getDate(), sd.getType().toString(), sd.getTotal(), sd.getId());
    }

    public Schedule getSchedule(int idSchedule) throws SQLException {
        ResultSet rs = executeQuery("SELECT * FROM SCHEDULE WHERE ID = ?", idSchedule);
        Schedule sd = null;
        if (rs.next()) {
            sd = populateSchedule(rs);
        }
        rs.close();
        return sd;
    }

    public static Schedule populateSchedule(ResultSet rs) throws SQLException {
        AnimalDAO animalDAO = new AnimalDAO();
        Schedule toReturn = new Schedule();
        toReturn.setId(rs.getInt("ID"));
        toReturn.setDate(rs.getDate("DATE"));
        toReturn.setTotal(rs.getFloat("TOTAL"));
        toReturn.setType(ScheduleType.valueOf(rs.getString("TYPE")));
        toReturn.setAnimal(animalDAO.getAnimal(rs.getInt("ID_ANIMAL")));
        return toReturn;
    }

    public List<Schedule> getSchedules() throws SQLException {
        List<Schedule> toReturn = new LinkedList<Schedule>();
        ResultSet rs = executeQuery("SELECT * FROM SCHEDULE");
        while (rs.next()) {
            toReturn.add(populateSchedule(rs));
        }
        rs.close();
        return toReturn;
    }
}
